<template>
  <div class="storeproduct-page page-main">
    <a-tabs v-model:activeKey="searchParams.type" @change="tabClick">
      <a-tab-pane v-for="(item) in headnum" :key="item.type" :tab="item.name + '(' + item.count + ')'" />
    </a-tabs>
    <search-form :model="searchParams" @search="search">
      <a-form-item label="商品分类：" name="address">
        <a-cascader v-model:value="cateIds" class="dialogWidth" clearable :options="cates"
          :field-names="{ label: 'name', value: 'id', children: 'child' }" />
      </a-form-item>
      <a-form-item label="商品搜索：" name="prop">
        <a-input v-model:value="searchParams.keywords" placeholder="请输入" />
      </a-form-item>
    </search-form>
    <div class="table-toolbar">
      <add-button @click="add()">添加商品</add-button>
      <a-button class="mr10" @click="onCopy">商品采集</a-button>
      <a-button class="mr10" @click="exports">导出</a-button>
    </div>
    <g-table ref="tableRef" :columns="columns" :api="getPageList" :isExtra="true" :params="searchParams">
      <template #expandedRow="{ record }">
        <a-form label-position="left" layout="inline" class="demo-table-expand">
          <a-form-item label="商品分类：">
            <span v-for="(item, index) in record.cateValues.split(',')" :key="index" class="mr10">{{ item }}</span>
          </a-form-item>
          <a-form-item label="市场价：">
            <span>{{ record.otPrice }}</span>
          </a-form-item>
          <a-form-item label="成本价：">
            <span>{{ record.cost }}</span>
          </a-form-item>
          <a-form-item label="收藏：">
            <span>{{ record.collectCount }}</span>
          </a-form-item>
          <a-form-item label="虚拟销量：">
            <span>{{ record.ficti }}</span>
          </a-form-item>
        </a-form>
      </template>
    </g-table>

    <storeproductDetail v-model:visible="visible" :data="activeRow" @change="search(false)" />
  </div>
</template>

<script setup lang="tsx">
import { storeproductDel, restoreApi, getPageList, productHeadersApi, categoryApi, putOnShellApi, productExcelApi, offShellApi } from './api';
import type { Istoreproduct } from './entity';
import storeproductDetail from './detail.vue';
import { Modal } from 'ant-design-vue';

const searchParams = reactive({
  type: 1,
  cateId: '',
  keywords: ''
})

let visible = $ref(false)
let cateIds = $ref([])
watch(
  () => cateIds,
  (val) => {
    if (val && val.length > 0) {
      let [last] = val.slice(-1)
      searchParams.cateId = last
    } else {
      searchParams.cateId = ''
    }
    search(false)
  }
);
const { tableRef, columns, search } = useTable<Istoreproduct>([
  { title: '标题', dataIndex: 'prop' },
  { title: 'ID', dataIndex: 'id' },
  {
    title: "商品图",
    dataIndex: "image",

    customRender: ({ record }) =>
      record.image ? <img class="img-thumbnail" src={record.image} /> : "",
  },
  { title: '商品名称', dataIndex: 'storeName' },
  { title: '商品售价', dataIndex: 'price' },
  { title: '销量', dataIndex: 'sales' },
  { title: '库存', dataIndex: 'stock' },
  { title: '排序', dataIndex: 'sort' },
  { title: '商品价格', dataIndex: 'price' },
  { title: '添加时间', dataIndex: 'addTime' },
  { title: "添加时间", dataIndex: "createTime" },
  {
    title: "状态",
    dataIndex: "isShow",
    width: 120,
    customRender: ({ record }) => (
      <>
        <a-switch
          onClick={() => updateState(record)}
          v-model:checked={record.isShow}
          inline-prompt
          checkedChildren="上架"
          unCheckedChildren="下架"
        />
      </>
    ),
  },
  {
    title: '操作',
    dataIndex: 'op',
    customRender: ({ record }) => (
      <>
        <table-button onClick={() => add(record)}>详情</table-button>
        <table-button onClick={() => add(record, true)}>编辑</table-button>
        {searchParams.type == 5 && <a-button type="text" size="small" onClick={() => handleRestore(record.id as number)}>恢复商品</a-button>}
        <a-button type="text" size="small" onClick={() => remove(record)} >{searchParams.type == 5 ? '删除' : '加入回收站'}</a-button>
      </>
    )
  }
])
async function tabClick(type: number) {
  searchParams.type = type
  search(false)
}
let activeRow = $ref<Partial<Istoreproduct>>({})
const router = useRouter()
function add(row: Partial<Istoreproduct> = {}, edt: boolean | string = '') {
  router.push({ path: `/store/creatProduct`, query: { id: row.id, edt: edt as string } });
}

function remove({ id }: Istoreproduct) {
  let type = searchParams.type
  const deleteFlag = type == 5 ? 'delete' : 'recycle';
  storeproductDel(id, deleteFlag).then(() => {
    AntMessage.success('已删除')
    search(false)
  })
}

onMounted(() => {
  queryGoodsHead()
  queryCate()
})
let headnum = $ref([{ type: '', name: '', count: '' }])
async function queryGoodsHead() {
  let data = await productHeadersApi()
  headnum = data
}
let cates = $ref()
async function queryCate() {
  let data = await categoryApi({ status: -1, type: 1 })
  cates = data
}
function onCopy(params: any) {

}

function updateState(row: Istoreproduct) {
  row.isShow
    ? putOnShellApi(row.id).then(() => {
      AntMessage.success('上架成功')
      queryGoodsHead()
      search(false)
    }).catch(() => {
      row.isShow = !row.isShow
    }) : offShellApi(row.id).then(() => {
      AntMessage.success('下架成功')
      queryGoodsHead()
      search(false)
    }).catch(() => {
      row.isShow = !row.isShow
    })
}
function exports(params: any) {
  let { cateId, keywords, type } = searchParams
  productExcelApi({ cateId, keywords, type }).then((res: any) => {
    window.location.href = res.fileName;
  })
}
function handleRestore(id: number) {
  Modal.confirm({
    title: '提示',
    content: '恢复商品',
    okText: '确认',
    cancelText: '取消',
    onOk() {
      restoreApi(id)
        .then((res) => {
          AntMessage.success('操作成功')
          queryGoodsHead()
          search(false)
        })
    }
  });
}
</script>

<style lang="scss"></style>